const mongoose = require('mongoose')
const tools = require('./tools')
const Schema = mongoose.Schema
const Question = {}


const questionSchema = Schema({
    text: String,
    keyword: String,
    createUser: {
        type: Schema.Types.ObjectId,
        ref: 'users'
    },
    createTime: Date,
    ip: String
})


Question.Model = mongoose.model('questions', questionSchema)


Question.listByPager = function (keyword, pageNo = 1, pageCount = 20) {
    if (pageNo < 1) throw new RangeError('参数 pageNo 不应小于 1。')
    if (pageCount < 1) throw new RangeError('参数 pageCount 不应小于 1。')

    var filter = {}
    if(keyword) filter.keyword = keyword

    return new Promise(function (resolve, reject) {
        Question.Model.find(filter)
            .sort('-createTime')
            .skip((pageNo - 1) * pageCount)
            .limit(pageCount)
            .populate({
                path: 'createUser',
                select: '-password'
            })
            .exec((err, models) => {
                if (err) {
                    reject(err)
                }
                else {
                    resolve(tools.toDatas(models))
                }
            })
    })
}


module.exports = Question
